package com.wang.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.dao.mapper.SysUserMapper;
import com.wang.pojo.Article;
import com.wang.pojo.SysUser;
import com.wang.vo.ErrorCode;
import com.wang.vo.LoginUserVo;
import com.wang.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private LoginService loginService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser findUserById(Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if(sysUser == null) {
            sysUser = new SysUser();
            sysUser.setNickname("码神之路");
        }
        return sysUser;
    }

    @Override
    public SysUser findUser(String account, String password) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getAccount, account);
        query.eq(SysUser::getPassword, password);
        query.select(SysUser::getAccount, SysUser::getId, SysUser::getAvatar, SysUser::getNickname);
        query.last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(query);
        return sysUser;
    }

    @Override
    public Result findUserByToken(String token) {
        if(token == null) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        SysUser sysUser = loginService.checkToken(token);
        LoginUserVo userVo = new LoginUserVo();
        BeanUtils.copyProperties(sysUser, userVo);
        return Result.success(userVo);
    }

    @Override
    public SysUser findUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, account);
        queryWrapper.last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        return sysUser;
    }

    @Transactional
    @Override
    public Boolean save(SysUser sysUser) {
        int insert = sysUserMapper.insert(sysUser);
        return insert != 0;
    }

}
